/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package threads;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Hnmtuan
 */
public class Waiting implements Runnable {

    private Integer _portNums;
    private ServerSocket _serverSocket;
    private Boolean _isWaiting;
    private Boolean _serverStatus;
    private Integer _peerNums;

    public Boolean getIsWaiting() {
        return _isWaiting;
    }

    public void setIsWaiting(Boolean _isWaiting) {
        this._isWaiting = _isWaiting;
    }

    public Integer getPeerNums() {
        return _peerNums;
    }

    public void setPeerNums(Integer _peerNums) {
        this._peerNums = _peerNums;
    }

    public Integer getPortNums() {
        return _portNums;
    }

    public void setPortNums(Integer _portNums) {
        this._portNums = _portNums;
    }

    public ServerSocket getServerSocket() {
        return _serverSocket;
    }

    public void setServerSocket(ServerSocket _serverSocket) {
        this._serverSocket = _serverSocket;
    }

    public Boolean getServerStatus() {
        return _serverStatus;
    }

    public void setServerStatus(Boolean _serverStatus) {
        this._serverStatus = _serverStatus;
    }

    public Waiting(Integer port, ServerSocket socket, Boolean waiting, Integer peer, Boolean status) {
        _portNums = port;
        _serverSocket = socket;
        _isWaiting = waiting;
        _peerNums = peer;
        _serverStatus = status;
    }

    public void run() {
        try {

            if (!_isWaiting) {
                _serverStatus = false;
                System.out.println("Server not set up waiting");
                return;
            }

            _serverSocket = new ServerSocket(_portNums);
            System.out.println("Waiting Client ... !");
            _serverStatus = true;

            while (_isWaiting) {
                Socket peer = _serverSocket.accept();

                if (peer == null) {
                    System.out.println("Failed in listen process");
                    System.exit(1);
                }

                new Thread(new Proccess(peer)).start();

                _peerNums += 1;

                System.out.println(String.format("Connecting Peer : %d", _peerNums));
            }

        } catch (IOException ex) {
            System.out.println(String.format("Failed in waiting thread : %s", ex.getMessage()));
        }
    }
}
